package com.imachen.ymcc.consumer;

import com.alibaba.fastjson.JSONObject;
import com.imachen.ymcc.domain.MessageSms;
import com.imachen.ymcc.dto.CourseSendMessageDto;
import com.imachen.ymcc.dto.UserSmsDto;
import com.imachen.ymcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

import static com.imachen.ymcc.constants.MqConstants.*;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "course-sms-consumer-group",
        topic = COURSE_SMS_TOPIC,
        selectorExpression = COURSE_SMS_TAG
)
public class CourseSmsMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 获取消息体
        byte[] body = messageExt.getBody();
        // 防御性编程,为空就直接返回
        if (body == null || body.length == 0){
            return;
        }
        // 转换消息体
        String messageStr = new String(body, StandardCharsets.UTF_8);
        CourseSendMessageDto courseSendMessageDto = JSONObject.parseObject(messageStr, CourseSendMessageDto.class);
        // 保存短信消息到t_message_sms
        saveMessageSms(courseSendMessageDto);
        // 发送信息
        log.info("发送短信成功！");
    }

    /**
     *  保存短信消息
     */
    private void saveMessageSms(CourseSendMessageDto courseSendMessageDto) {
        String content = courseSendMessageDto.getContent();
        String title = courseSendMessageDto.getTitle();
        List<UserSmsDto> userSmsDtos = courseSendMessageDto.getUserSmsDtos();

        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(title);
        messageSms.setContent(content);
        messageSms.setSendTime(new Date());
        userSmsDtos.forEach(e->{
            messageSms.setUserId(e.getId());
            messageSms.setPhone(e.getPhone());
            messageSmsService.insert(messageSms);
        });

    }
}
